# coding = utf-8

'''
测试膨胀腐蚀算法的有效性
'''

import cv2,os
import numpy as np
import matplotlib.pyplot as plt
import SimpleITK as sitk
from PIL import Image
import math

def find_data(case_id, origion_id, index):
    big_image = "E:\Dataset\Liver\qiye\DongBeiDaXue2\image_venous\\data2_{}_venous.mha".format(origion_id)
    big_liver = "E:\Dataset\Liver\qiye\DongBeiDaXue2\liver\\data2_{}_liver_label.mha".format(origion_id)
    big_tumor = "E:\Dataset\Liver\qiye\DongBeiDaXue2\lesion\\data2_{}_lesion_label.mha".format(origion_id)
    big_fusion = "E:\predict\image_tumor\case_{}\\fusion\\{}.png".format(str(case_id).zfill(5), str(index).zfill(3))
    big_image = sitk.GetArrayFromImage(sitk.ReadImage(big_image))
    big_image[big_image <= -200] = -200
    big_image[big_image > 250] = 250
    big_image = (big_image + 200) / 450
    big_image = big_image[index]
    big_liver = sitk.GetArrayFromImage(sitk.ReadImage(big_liver))
    big_liver = big_liver[index]
    big_tumor = sitk.GetArrayFromImage(sitk.ReadImage(big_tumor))
    big_tumor = big_tumor[index]
    big_fusion = Image.open(big_fusion)
    return (big_image, big_fusion, big_liver, big_tumor)

def eroade():
    (big_image, big_fusion, big_liver, big_tumor) = find_data(case_id=72, origion_id="0628", index=142)

    big_liver = big_liver * 255
    big_liver = big_liver.astype(np.uint8)

    kernel = np.ones((15, 15), np.uint8)
    erosion = cv2.erode(big_liver, kernel, iterations=1)

    erosion = cv2.cvtColor(erosion, cv2.COLOR_GRAY2BGR)

    contours, _ = cv2.findContours(big_liver, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(erosion, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    plt.imshow(erosion)
    plt.show()


if __name__ == '__main__':
    eroade()